<template>
  <el-dialog
    v-model="visible"
    :title="$t('contacts.groups.title')"
    width="500px"
    :before-close="handleClose"
  >
    <div class="groups-list">
      <div v-if="groups.length === 0" class="empty-state">
        <el-empty :description="$t('contacts.groups.noGroups')" />
      </div>
      
      <div v-else>
        <div 
          v-for="group in groups" 
          :key="group.id"
          class="group-item"
        >
          <div class="group-info">
            <div class="group-name">{{ group.groupName }}</div>
            <div class="group-meta">
              <span class="friend-count">{{ group.friendCount }} {{ $t('contacts.stats.friends') }}</span>
              <span v-if="group.description" class="group-desc">{{ group.description }}</span>
            </div>
          </div>
          
          <div class="group-actions">
            <el-button 
              text 
              type="danger" 
              size="small"
              @click="handleDeleteGroup(group)"
              :disabled="group.groupName === $t('contacts.groups.defaultGroup')"
            >
              {{ $t('common.delete') }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ $t('common.close') }}</el-button>
        <el-button type="primary" @click="handleRefresh">{{ $t('common.refresh') }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { contactsApi } from '@/api/contacts'
import { useContactsStore } from '@/stores/contacts'

// Props & Emits
const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'updated': []
}>()

// 状态管理
const contactsStore = useContactsStore()

// 响应式数据
const groups = ref<any[]>([])
const loading = ref(false)

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听对话框显示状态
watch(visible, (newVisible) => {
  if (newVisible) {
    loadGroups()
  }
})

// 方法
const loadGroups = async () => {
  try {
    loading.value = true
    const response = await contactsApi.getFriendGroupsDetail()
    groups.value = response.data || []
    console.log('✅ 分组详情加载成功:', response)
  } catch (error) {
    console.error('❌ 加载分组详情失败:', error)
    ElMessage.error('加载分组信息失败')
    groups.value = []
  } finally {
    loading.value = false
  }
}

const handleDeleteGroup = async (group: any) => {
  if (group.groupName === t('contacts.groups.defaultGroup')) {
    ElMessage.warning(t('contacts.groups.cannotDeleteDefault'))
    return
  }

  try {
    await ElMessageBox.confirm(
      t('contacts.groups.deleteConfirm', { name: group.groupName }) + t('contacts.groups.deleteWarning'),
      t('contacts.groups.deleteGroup'),
      {
        confirmButtonText: t('contacts.groups.confirmDelete'),
        cancelButtonText: t('common.cancel'),
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    await contactsApi.deleteFriendGroup(group.id)
    ElMessage.success('分组删除成功')

    // 重新加载分组列表
    await loadGroups()

    emit('updated')

  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除分组失败:', error)
      ElMessage.error(error.response?.data?.message || '删除分组失败')
    }
  }
}

const handleRefresh = () => {
  loadGroups()
}

const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.groups-list {
  max-height: 400px;
  overflow-y: auto;
}

.group-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid var(--el-border-color-extra-light);
}

.group-item:last-child {
  border-bottom: none;
}

.group-info {
  flex: 1;
}

.group-name {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
}

.group-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.friend-count {
  color: var(--el-color-primary);
}

.group-desc {
  color: var(--el-text-color-secondary);
}

.group-actions {
  flex-shrink: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .group-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .group-actions {
    align-self: flex-end;
  }
}
</style>
